<?php
class Tricky
{
	protected $req;
	protected $data;

	public function __construct($req){
		$this->req  = $this->_getSani($req);
		$this->data = new ArrayObject;
	}

	public function action(){
		try{
			$this->_execute();
		}catch(Exception $e){
			$this->data->offsetSet('msg', $e->getMessage());
			$this->data->offsetSet('cd', $e->getCode());
		}
		return $this->data;
	}

	/* Override */
	protected function _execute(){
		$default = explode('/', 'index/index');
		$role = explode('/', $this->req->get('r'));
		$c = (isset($role[0]))? $role[0] : $default[0];
		$a = (isset($role[1]))? $role[1] : $default[1];

		$s = $this->req;
		$v = $this->_getVali();

		try{
			$this->_get($c)
				 ->set($v)
				 ->set($s)
				 ->exe($a);
		}catch(TView $view){
			if($view->isTemplate()){
				$view->show();
			}
		}catch(EView $view){
			$this->data->offsetSet('msg', $view->getMessage());
			$this->data->offsetSet('cd', $view->getCode());
		}
	}

	protected function _get($c){
		if($c == 'index'){
			$c = 'TController';
		}else{
			$c = ucfirst($c);
		}
		if(!class_exists($c)){
			throw EView::getI();
		}
		$i = new $c;
		if(!($i instanceof TController)){
			throw new Exception('No TController error', 1);
		}
		return $i;
	}

	protected function _getSani($req){
		return new TSanitize($req);
	}

	protected function _getVali(){
		require_once(PLUGIN_DIR.'/TValidate.php');
		return new TValidate;
	}

	public function index(){
		throw TView::getI();
	}
}
